package com.rp.api.interceptors;

import com.rp.news.common.ResponseStatusEnum;
import com.rp.news.exception.GraceException;
import com.rp.news.util.IPUtil;
import com.rp.news.util.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PassportInterceptor implements HandlerInterceptor {


    @Autowired
    public RedisOperator redis;


    public static final String SMS_CODE = "sms:code";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestIp = IPUtil.getRequestIp(request);
        boolean flag = redis.keyIsExist(SMS_CODE + ":" + requestIp);
        if(flag){
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
            return false;
        }

        // true: 放行  false:阻止
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
